package com.taobao.ued.toy.dao;


import com.taobao.ued.toy.domain.Pic;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Service
public class JdbcPicDao implements PicDao {
	Log logger = LogFactory.getLog(getClass());
	private SimpleJdbcTemplate jdbcTemplate;

	@Autowired
	public void setDataSource(DataSource dataSource) {
		this.jdbcTemplate = new SimpleJdbcTemplate(dataSource);
	}

	private SimpleJdbcTemplate getSimpleJdbcTemplate() {
		return this.jdbcTemplate;
	}

	static String[] FIELDS = new String[]{
			"workId",
			"cover",
			"url",
			"description"
	};

	static String[] PARAMS = DaoUtils.getFieldsForParams(FIELDS);

	public void add(Pic p) throws Exception {
		logger.info("add pic: ");

		MapSqlParameterSource params = DaoUtils.getParamSource(p, FIELDS);

		String sql = "insert into pics (" + StringUtils.join(FIELDS, ",") + ") " +
				"values (" + StringUtils.join(PARAMS, ",") + ")";

		int count = getSimpleJdbcTemplate().update(sql, params);

		logger.info("Rows pics: " + count);
	}

	public List<Pic> getsByWork(int workId) {

		List<Pic> ds = getSimpleJdbcTemplate().query("select * from pics where workId = :workId",
				new PicMapper(),
				new MapSqlParameterSource().addValue("workId", workId));
		logger.info("getsByWork end");
		return ds;
	}

	static class PicMapper implements ParameterizedRowMapper<Pic> {

		public Pic mapRow(ResultSet rs, int rowNum) throws SQLException {
			Pic prod = new Pic();
			prod.setId(rs.getInt("id"));
			try {
				DaoUtils.copyBeanFromRs(prod, rs, FIELDS);
			} catch (Exception e) {
				throw new SQLException(e);
			}
			return prod;
		}
	}
}
